<template>
  <div class="login_container">
    <div class="login_box">
      <!-- login 头像区域 -->
      <div class="avatar_box">
        <img src="../assets/logo.png" alt />
      </div>
      <!-- 登录 -->
      <div class="add_box">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
          <el-form-item label="账号" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="info" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {},
  data() {
    return {
      form: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入正确的账号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入正确的密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    // 重置
    reset() {
      this.$refs.form.resetFields()
    },
    // 登录
    login() {
      // console.log(form);
      this.$refs.form.validate(async val => {
        if (!val) return
        let res = await this.$axios.post('login', this.form)
        // console.log(res);
        if (res.data.meta.status !== 200) {
          return this.$message.error('登录失败！')
        }
        this.$message.success('登录成功！')

        //1. 设置token只有在网站打开期间生效
        window.sessionStorage.setItem('token', res.data.data.token)
        //2. 通过完成登录后进行页面的跳转
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.login_container {
  background-color: #2b4b6b;
  height: 100%;
}
.login_box {
  width: 450px;
  height: 300px;
  background: #ffffff;
  border-radius: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .avatar_box {
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 130px;
    height: 130px;
    border: 1px solid #cccccc;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #dddddd;
    background: #ffffff;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: #eeeeee;
    }
  }
  .add_box {
    margin-top: 100px;
    .el-form {
      padding-right: 20px;
    }
  }
}
</style>

